package com.example.venue_reservation_service.utils;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Scanner;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JsonNode;

public class AIChatClient {
    private static final String API_URL = "https://chat.intern-ai.org.cn/api/v1/chat/completions";
    private static final String BEARER_TOKEN = "eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFM1MTIifQ.eyJqdGkiOiI4NjMwNjcyNyIsInJvbCI6IlJPTEVfUkVHSVNURVIiLCJpc3MiOiJPcGVuWExhYiIsImlhdCI6MTc1MTUzOTEzNCwiY2xpZW50SWQiOiJlYm1ydm9kNnlvMG5semFlazF5cCIsInBob25lIjoiMTc4NzAzNDI2ODUiLCJvcGVuSWQiOm51bGwsInV1aWQiOiIzNDg5ZTJkOC04ZGI4LTQyNDUtOTFiZC03YmRkN2Y3MTI0ZDEiLCJlbWFpbCI6IiIsImV4cCI6MTc2NzA5MTEzNH0.-Bfg41q0v4RDjN6mgfLmga1isL02KF5DdoA1LoiNmUQg8I19FjEMz2w9dOJsql3-MavE6UB5QlECQiDvk4t6XQ"; // 替换为你的实际Token
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 初始化对话历史
        String conversationHistory = buildInitialHistory();

        while (true) {
            System.out.print("\n请输入你的问题 (输入 'exit' 退出): ");
            String userInput = scanner.nextLine();

            if ("exit".equalsIgnoreCase(userInput)) {
                break;
            }

            // 更新对话历史
            conversationHistory = updateHistory(conversationHistory, userInput);

            try {
                // 发送请求并获取响应
                String response = sendChatRequest(conversationHistory);

                // 更新对话历史（添加AI回复）
                conversationHistory = conversationHistory +
                        ",{\"role\":\"assistant\",\"content\":\"" + escapeJson(response) + "\"}";

                System.out.println("\nAI回复: " + response);
            } catch (Exception e) {
                System.err.println("请求失败: " + e.getMessage());
            }
        }

        scanner.close();
    }

    private static String sendChatRequest(String history) throws Exception {
        // 构建完整的请求体
        String requestBody = String.format(
                "{\"model\":\"internlm3-latest\",\"messages\":[%s],\"temperature\":0.8,\"top_p\":0.9,\"stream\":true}",
                history
        );

        // 创建HTTP请求
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .header("Authorization", "Bearer " + BEARER_TOKEN)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

        // 发送请求并处理流式响应
        StringBuilder fullResponse = new StringBuilder();
        client.send(request, HttpResponse.BodyHandlers.ofLines()).body()
                .filter(line -> line.startsWith("data:") && !line.contains("[DONE]"))
                .forEach(line -> {
                    try {
                        String json = line.substring(5).trim();
                        if (!json.isEmpty()) {
                            JsonNode node = objectMapper.readTree(json);
                            String content = node.path("choices").get(0).path("delta").path("content").asText();
                            if (content != null && !content.isEmpty()) {
                                System.out.print(content); // 实时输出
                                fullResponse.append(content);
                            }
                        }
                    } catch (Exception e) {
                        System.err.println("\n解析错误: " + e.getMessage());
                    }
                });

        return fullResponse.toString();
    }

    private static String buildInitialHistory() {
        return "{\"role\":\"user\",\"content\":\"你知道刘慈欣吗？\"}," +
                "{\"role\":\"assistant\",\"content\":\"为一个人工智能助手，我知道刘慈欣。他是一位著名的中国科幻小说家和工程师，曾经获得过多项奖项，包括雨果奖、星云奖等。\"}";
    }

    private static String updateHistory(String history, String newQuestion) {
        return history + ",{\"role\":\"user\",\"content\":\"" + escapeJson(newQuestion) + "\"}";
    }

    private static String escapeJson(String input) {
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }
}